<template>
  <div class="work_shop_bench">
    <!--技术文件-->
    <technical-documents ref="technicalDocuments"></technical-documents>
    <!--生产补料-->
    <produce-supply ref="ProduceSupply" @submitSuccess="refresh"></produce-supply>
    <!--问题反馈-->
    <problem-feedback ref="ProblemFeedback" @submitSuccess="refresh"></problem-feedback>
    <!--获取序列号-->
    <get-serial-number ref="GetSerialNumber" @submitSuccess="init"></get-serial-number>
    <!--参数记录-->
    <work-stage-param-record ref="WorkStageParamRecord" @submitSuccess="init"></work-stage-param-record>
    <!--工序上料-->
    <work-stage-material ref="WorkStageMaterial" @submitSuccess="init"></work-stage-material>
    <!--开工登记-->
    <work-stage-start ref="workStageStart" @submitSuccess="init"></work-stage-start>
    <!--完工登记-->
    <complete-register ref="CompleteRegister" @submitSuccess="init"></complete-register>
    <!--设备状态-->
    <equipment-state ref="EquipmentState" @submitSuccess="init"></equipment-state>
    <!--作业环境记录-->
    <record-clean-room ref="RecordCleanRoom"></record-clean-room>
    <!--工序进度-->
    <workstage-proccess ref="WorkstageProccess"></workstage-proccess>
    <one-title :title="titleText" @refreshData="refresh">
      <div class="mes_btn">
        <el-button
          v-btn-permission="'recordCleanRoom'"
          @click="recordCleanRoom">
          <i class="iconfont icon-jiejingjianjilu"></i>
          作业环境记录
        </el-button>
        <el-button
          v-btn-permission="'equipmentState'"
          @click="equipmentState">
          <i class="iconfont icon-shebeizhuangtai"></i>
          设备状态
        </el-button>
        <disabled-btn
          v-btn-permission="'getSerialNumber'"
          :judge="serialNumberBtnStatus"
          iconClass="iconfont icon-huoquxuliehao"
          btnText="获取序列号"
          @judgeClick="getSerialNumber"></disabled-btn>
        <disabled-btn
          v-btn-permission="'paramRecord'"
          :judge="paramBtnStatus"
          iconClass="iconfont icon-canshujilu1"
          btnText="参数记录"
          @judgeClick="paramRecord"></disabled-btn>
        <disabled-btn
          v-btn-permission="'workStageMaterial'"
          :judge="materialBtnStatus"
          iconClass="iconfont icon-btn_export"
          btnText="工序上料"
          @judgeClick="WorkStageMaterial"></disabled-btn>
        <disabled-btn
          v-btn-permission="'completeRegister'"
          :judge="completeBtnStatus"
          iconClass="iconfont icon-btn_Save"
          btnText="完工登记"
          btnType="primary"
          @judgeClick="completeRegister"></disabled-btn>
        <disabled-btn
          v-btn-permission="'workStart'"
          :judge="startBtnStatus"
          iconClass="iconfont icon-kaigongdengji"
          btnText="开工登记"
          btnType="success"
          @judgeClick="workStart"></disabled-btn>
      </div>
    </one-title>
    <div class="fixed_top_56">
      <mes-search-comp
        ref="mesSearch"
        code-placeholder="[周转码]/[工序编码]/[工序序号]"
        :code-scan="true"
        :searchList="searchList"
        :searchResult="searchResult"
        :showSlotSet="true"
        :showSlotExport="true"
        @codeSubmit="handleCodeScan"
        @setCol="$refs.ColumnControl.openDialog()"
        @exportTable="_exportTable"
        @searchInfo="_info">
      </mes-search-comp>
      <!--工作台列表-->
      <div class="table_container">
        <el-table
          ref="tableNode"
          :data="listData.list"
          border
          stripe
          v-loading="isLoading"
          style="width: 100%"
          :max-height="tableMaxHeight"
          :cell-class-name="setCellClass"
          :row-class-name="({row}) => !selectData.some((item) => item.id === row.id) || 'line_selected'"
          @row-click="row => $refs.tableNode.toggleRowSelection(row)"
          @sort-change="_sort"
          @selection-change="handleSelectionChange"
          @filter-change="handleFilterChange">
          <el-table-column
            align="center"
            type="selection"
            :disabled="true"
            width="40">
          </el-table-column>
          <mes-col-comp
            :key="index"
            v-for="(column, index) in columnList"
            :column="column"
            @jump="row => handleWorkstageProccess([row])">
          </mes-col-comp>
          <el-table-column
            prop="parameterRecordId"
            v-if="!checkedKeys || checkedKeys.includes('parameterRecordId')"
            align="center"
            sortable="custom"
            label="参数记录"
            min-width="120">
            <template slot-scope="scope">
              {{scope.row.parameterRecordId ? '已记录' : '未记录'}}
            </template>
          </el-table-column>
          <el-table-column
            fixed="right"
            :resizable="false"
            label="操作"
            class-name="operation_btn"
            min-width="120">
            <template slot-scope="scope">
              <el-tooltip class="item" effect="dark" content="技术文件" :open-delay="openDelay" placement="bottom">
                <div>
                  <el-button type="text" size="small" @click.stop="telDocCheck(scope.row)" class="jump_item">
                    <i class="iconfont icon-jishuwenjianchakan"></i>
                  </el-button>
                </div>
              </el-tooltip>
              <el-tooltip
                class="item"
                effect="dark"
                content="生产补料"
                popper-class="btn_tooltip"
                :open-delay="openDelay"
                placement="bottom">
                <div>
                  <el-button
                    :disabled="checkBtnStatus(scope.row, 1)"
                    type="text"
                    size="small"
                    @click.stop="produceSupply(scope.row)"
                    class="jump_item">
                    <i class="iconfont icon-shengchanbuliao"></i>
                  </el-button>
                </div>
              </el-tooltip>
              <el-tooltip
                class="item"
                effect="dark"
                content="问题反馈"
                popper-class="btn_tooltip"
                :open-delay="openDelay"
                placement="bottom">
                <div>
                  <el-button
                    :disabled="checkBtnStatus(scope.row, 2)"
                    type="text"
                    size="small"
                    @click.stop="problemFeedback(scope.row)"
                    class="jump_item">
                    <i class="iconfont icon-wentifankui"></i>
                  </el-button>
                </div>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!--分页组件-->
      <mes-pagination
        @updateData="init"
        :currentPage="listData.pageNo"
        :total="listData.count || 0"
        :pageSize="listData.pageSize">
      </mes-pagination>
      <!-- 日志详情 -->
      <log-detail ref="logDetail"></log-detail>
      <!--列隐藏-->
      <column-control
        ref="ColumnControl"
        :colList="searchList"
        @saveCol="saveCol"
      ></column-control>
    </div>
  </div>
</template>

<script>
import searchList from './columns'
import {
  RecordCleanRoom,
  EquipmentState,
  GetSerialNumber,
  WorkStageMaterial,
  WorkStageStart,
  ProduceSupply,
} from '../workshopBenchComps'
import workbenchBtnService from '../workshopBenchComps/workbenchBtnService'
// 完工登记
//import CompleteRegister from '@/components/completion/CompleteRegister'
//import CompleteRegister from '@/components/completion/CompleteRegister'
import {WorkStageParamRecord} from '@/components/Template'
import ProblemFeedback from '@/components/workbenchComps/ProblemFeedback'
import TechnicalDocuments from '@/components/workbenchComps/TechnicalDocuments'
import WorkstageProccess from '@/components/workbenchComps/WorkstageProccess'
import {CompleteRegister} from '@/components/completion';

export default {
  name: 'WorkshopBench',
  mixins: [workbenchBtnService],
  components: {
    GetSerialNumber,
    TechnicalDocuments,
    ProduceSupply,
    ProblemFeedback,
    WorkStageParamRecord,
    WorkStageMaterial,
    WorkStageStart,
    CompleteRegister,
    EquipmentState,
    RecordCleanRoom,
    WorkstageProccess,
  },
  data() {
    return {
      titleText: '操作者工作台', // 模块标题
      selectData: [], // 选中的表格数据
      searchData: {}, // 搜索列表数据
      searchResult: NaN, // 搜索结果数
      isLoading: false, // 是否加载完毕
      sortData: {}, // 排序字段
      checkedKeys: window.localStorage.getItem(this.$route.name) || '', // 显示的列集合
    }
  },
  computed: {
    listData() {
      return this.$store.state.workshopBench.listData
    },
    searchList,
    // 列循环
    columnList() {
      this.$nextTick(() => {
        this.$refs.tableNode.doLayout()
      })
      let checkedKeysList = this.checkedKeys ? JSON.parse(this.checkedKeys) : this.searchList.reduce((pre, cur) => [...pre, cur.prop], [])
      return this.searchList.filter(item => item.noForCol !== true && (item.noChecked === true || checkedKeysList.some(key => key === item.prop)))
    },
  },
  mounted() {
    this.init()
  },
  methods: {
    // 列筛选回调
    handleFilterChange(filters) {
      this.sortData = {}
      this.$refs.tableNode.clearSort()
      let filterParams = this.$filterParams(this.searchList, filters)
      Object.assign(this.searchData, filterParams.search)
      Object.assign(this.sortData, filterParams.order)
      this.init()
    },
    // 修改列显示
    saveCol(checkedKeys) {
      this.checkedKeys = checkedKeys
    },
    // 刷新列表
    refresh() {
      this.$refs.mesSearch.clean()
      this.$refs.tableNode.clearSort()
      this.$refs.tableNode.clearFilter()
      this.searchData = {}
      this.sortData = {}
      this.init()
    },
    // 导出表格
    _exportTable() {
      let postData = this.formatPostData({
        pageNo: 1,
        pageSize: 9999999
      }, [])
      this.$exportTable(postData, 'a/turnoverworkstage/turnoverWorkstage/exportasexcel', this.titleText)
    },
    // 格式化数据
    formatPostData(page, fields) {
      const list = this.searchList.filter((item) => item.noExport !== true)
      let postData = {
        pageNo: page ? page.pageNo : 1,
        pageSize: page ? page.pageSize : this.listData.pageSize || 15,
        sort: this.sortData,
        query: {
          columns: list.reduce((pre, cur) => [...pre, cur.prop], fields),
          inspectionTypeId: this.inspectionId,
          turnoverProcessStatusId: this.batchProcessStatusIds,
          ...this.searchData
        }
      }
      return postData
    },
    /**
     * 列表数据获取
     * @param page
     */
    init(page) {
      const fields = ['inputQuantity', 'scrapQuantity', 'startWorkStaffId', 'turnoverId', 'paramTemplateId', 'workorderId', 'workstageId', 'productBatchNumber', 'sort', 'workstageNumber', 'parameterRecordId']
      let postData = this.formatPostData(page, fields)
      this.isLoading = true
      this.$store.dispatch('saveData', {
        method: 'post',
        url: 'a/turnoverworkstage/turnoverWorkstage/list',
        data: postData,
        module: 'workshopBench',
        state: 'listData'
      }).then((res) => {
        if (Object.keys(this.searchData).length > 0) {
          this.searchResult = res.count
        } else {
          this.searchResult = NaN
        }
      }).finally(() => {
        this.isLoading = false
        this.$nextTick(() => {
          this.$refs.WorkstageProccess.dialogVisible = false
        })
      })
    },
    /**
     * 选择勾选
     * @param value
     */
    handleSelectionChange(value) {
      this.selectData = value
    },
    /**
     * 查询
     * @param data
     */
    _info(data) {
      this.$refs.tableNode.clearSort()
      this.$refs.tableNode.clearFilter()
      this.sortData = {}
      this.searchData = data
      this.init()
    },
    // 扫码刷新
    handleCodeScan(value) {
      this.$refs.mesSearch.clean()
      let strList = value.split('/')
      if (strList.length === 3) {
        this.searchData = {
          turnoverNumber: strList[0],
          workstageNumber: strList[1],
          sort: strList[2]
        }
        this.init()
      } else {
        this.tipMessage('error', '无效搜索码')
      }
    },
    // 排序
    _sort(obj) {
      this.sortData = this.$getSortOrder(obj)
      this.init()
    },
    /**
     * 检查生产补料和问题反馈按钮的disabled状态
     * @param row 表格行数据
     * @param type 操作类型,1:补料；2:问题反馈
     */
    checkBtnStatus(row, type) {
      if (row) {
        let baseStatus = row.turnoverStatusValue !== 'Normal' || row.workstageProcessStatusValue === 'Finished' || row.workstageProcessStatusValue === 'NotArrive'
        let result = false
        if (type === 2) {
          result = baseStatus || row.taskTypeValue === 'Rework'
        } else {
          result = baseStatus || row.materialStatusValue === 'Unneeded'
        }
        // 工序已开工有开工人员id
        if (row.startWorkStaffId) {
          return result || this.userId !== row.startWorkStaffId
        }
        return result
      }
    },
    // 设置单元格样式
    setCellClass({row, column}) {
      let isAfter = this.moment(row.planEndDate).isBefore(window.serverTime)
      if (isAfter && column.property === 'planEndDate') {
        return 'cell_isAfter'
      }
    },
    /**
     * 技术文档查看
     * @param row 当前行数据
     */
    telDocCheck(row) {
      this.$refs.technicalDocuments.openDialog(row)
    },
    /**
     * 生产补料
     * @param row 当前行数据
     */
    produceSupply(row) {
      this.$refs.ProduceSupply.openDialog(row)
    },
    // 问题反馈
    problemFeedback(row) {
      this.$refs.ProblemFeedback.openDialog(row)
    },
    // 日志
    showLog(row) {
      this.$refs.logDetail.openDialog({
        title: '周转码',
        name: row.turnoverNumber,
        url: 'a/turnoverstatuschangehistory/turnoverStatusChangeHistory/list',
        query: {
          turnoverBatchId: row.turnoverId
        }
      })
    },

    /**
     * 工序进度
     */
    handleWorkstageProccess(row) {
      this.$refs.WorkstageProccess.openDialog(row)
    },
    /**
     * 提示
     * @param type 提示类型
     * @param str 提示内容
     */
    tipMessage(type, str) {
      this.$message({
        type: type,
        message: str,
        duration: 1500,
        center: true
      })
    }
  }
}
</script>

<style lang="less">
  .work_shop_bench {
    .cell_isAfter {
      span.mes_cell {
        color: #f8000f;
      }
    }
    .fixed_btn {
      margin-left: -6px;
    }
    .assigned_to_me {
      border: none !important;
      color: #00b4ff !important;
      font-size: 14px;
      font-weight: 600;
      &:hover {
        background-color: #fff !important;
        color: #00b4ff !important;
      }
      &.is_actived {
        background-color: #e8f4fe !important;
      }
    }
  }
</style>
